#include "myoperate.h"

char *reverse( char *toreverse ){
    char *a = toreverse, *b = a + strlen(toreverse) - 1 , temp ;
    while( a < b ){
        temp = *a;
        *a++ = *b;
        *b-- = temp;
    }
    return toreverse;
}

long char_to_num( char *s ){
    char *p = s;
    long ans = 0;
    int is_negative = 0;
    if( *p == '-' ){
        is_negative = 1;
        p++;
    }
    while( *p != '\0' ){
        ans *= 10;
        ans += *p - '0';
        p++;
    }
    if(is_negative){
        return 0-ans;
    }
    return ans;
}

char *num_to_char( long num ){
    int is_negative = 0;
    if(num<0){
        is_negative = 1;
        num = 0-num;
    }else if(num==0){
        return "0";
    }
    char *ans = malloc( sizeof(long) ), *p = ans;
    while(num){
        *p = num % 10 + '0';
        num /= 10;
        p++;
    }
    if(is_negative){
        *p++ = '-';
    }
    *p = '\0';
    return reverse(ans);
}

char *myoperate( char *a, char *b, char myoperator ){
    long x = char_to_num(a), y = char_to_num(b);
    char *ans = malloc( sizeof(char) * 1000 );

    switch(myoperator){
        case '+':
            ans = num_to_char( x+y );
            break;
        case '-':
            ans = num_to_char( x-y );
            break;
        case '*':
            ans = num_to_char( x*y );
            break;
        case '/':
            ans = num_to_char( x/y );
            break;
        default:
            printf("undefined operator\n");
    }

    return ans;
}
